package com.zhang.service;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhang.entity.BugRegister;
import com.zhang.entity.dto.CompleteMissionDto;
import com.zhang.entity.dto.MissionDto;
import com.zhang.entity.dto.MyBugMissionDto;
import com.zhang.entity.dto.QueryBugDto;
import com.zhang.entity.vo.*;
import com.zhang.exception.ServiceException;
import com.zhang.mapper.BugRegisterMapper;
import com.zhang.mapper.MissionPersonMapper;
import com.zhang.util.FileHandleUtils;
import com.zhang.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.zhang.common.Constant.*;

/**
 * User: 张
 * Date: 2024-11-07
 * Time: 18:46
 * Description:
 */

@Service
public class TaskService {

    @Autowired
    private FileHandleUtils fileHandleUtils;
    @Autowired
    private BugRegisterMapper bugRegisterMapper;
    @Autowired
    private TimeUtil timeUtil;
    @Autowired
    private MissionPersonMapper missionPersonMapper;

    public PageInfo<QueryBugReturnBody> queryBugMessage(QueryBugBody queryBugBody, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        // 检查日期格式
        QueryBugDto queryBugDto = new QueryBugDto(
                queryBugBody.getUserName(),
                timeUtil.checkTimeFormat(queryBugBody.getBugTime()),
                queryBugBody.getVersion()
        );
        // 查询故障数据，将返回结果封装成QueryBugReturnBody，因为path是JSON数组，不能直接返回，需要先转为List再返回
        List<QueryBugReturnBody> bugResult = new ArrayList<>();
        for (BugRegister bugRegister : bugRegisterMapper.queryBugMessage(queryBugDto)) {
            QueryBugReturnBody queryBugReturnBody = new QueryBugReturnBody(
                    bugRegister.getId(),
                    bugRegister.getUserId(),
                    bugRegister.getDeviceId(),
                    bugRegister.getBugDescription(),
                    JSON.parseArray(bugRegister.getFileName(), String.class),  // 将JSON字符串转为List
                    bugRegister.getBugTime(),
                    bugRegister.getVersion()
            );
            bugResult.add(queryBugReturnBody);
        }
        return new PageInfo<>(bugResult);
    }

    public Boolean registerBugMessage(MultipartFile[] filesUpload, BugRegisterBody bugRegister) {
        //  检查时间格式是否正确
        Date time = timeUtil.checkTimeFormat(bugRegister.getBugTime());
        //  保存图片
        String pathJson = null;
        if (filesUpload != null) {
            pathJson = JSON.toJSONString(fileHandleUtils.fileUpload(filesUpload));
        }
        // 保存数据
        BugRegister bugMessage = new BugRegister();
        bugMessage
                .setUserId(StpUtil.getLoginIdAsInt())
                .setDeviceId(bugRegister.getDeviceId())
                .setBugDescription(bugRegister.getBugDescription())
                .setFileName(pathJson)
                .setBugTime(time == null ? new Date() : time)
                .setVersion(BUG_NOT_REPAIR);
        return bugRegisterMapper.addBugMessage(bugMessage) > ZERO;
    }

    public ResponseEntity<byte[]> fileDownload(String fileName){
        String[] split = fileName.split("\\\\");
        return fileHandleUtils.fileDownload(split[split.length - 1]);
    }

    public Boolean dispatchMission(DispatchMissionBody dispatchMission){
        return missionPersonMapper.addMissionPerson(dispatchMission) > ZERO;
    }

    public PageInfo<MyBugMissionBody> getMyBugMission(Integer userId,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<MyBugMissionBody> myBugMissionBodyList = new ArrayList<>();
        for (MyBugMissionDto myBugMissionDto : missionPersonMapper.getMyBugMission(userId)) {
            myBugMissionBodyList.add(new MyBugMissionBody(
                    myBugMissionDto.getId(),
                    myBugMissionDto.getDeviceId(),
                    myBugMissionDto.getDeviceName(),
                    myBugMissionDto.getBugDescription(),
                    JSON.parseArray(myBugMissionDto.getFileName(), String.class),
                    myBugMissionDto.getBugTime(),
                    myBugMissionDto.getVersion(),
                    myBugMissionDto.getMessage()
            ));
        }
        return new PageInfo<>(myBugMissionBodyList);
    }

    public Boolean completeMission(CompleteMissionBody completeMissionBody,MultipartFile[] filesUpload){
        //  检查时间格式是否正确
        Date time = timeUtil.checkTimeFormat(completeMissionBody.getTime());
        //  保存图片
        String pathJson = null;
        if (filesUpload != null) {
            pathJson = JSON.toJSONString(fileHandleUtils.fileUpload(filesUpload));
        }
        CompleteMissionDto completeMissionDto = new CompleteMissionDto(
                StpUtil.getLoginIdAsInt(),
                completeMissionBody.getMissionId(),
                time,
                completeMissionBody.getMessage(),
                pathJson
        );
        return missionPersonMapper.completeMission(completeMissionDto) > ZERO;
    }

    public PageInfo<MissionDto> getMission(Integer pageNum, Integer pageSize ,MissionBody missionBody){
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(missionPersonMapper.getMission(missionBody));
    }

    public Boolean changeBugVersion(BugVersionBody bugVersionBody){
        return bugRegisterMapper.changeBugVersion(bugVersionBody.getBugId(), bugVersionBody.getVersion());
    }
}
